/**
 * Copyright (c) 2018-2028, HQY 胡庆一 (215218393@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ocm.warehouse.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ocm.core.log.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import com.ocm.core.mp.support.Condition;
import com.ocm.core.mp.support.Query;
import com.ocm.core.secure.BladeUser;
import com.ocm.core.tool.api.R;
import com.ocm.core.tool.utils.BeanUtil;
import com.ocm.core.tool.utils.Func;
import com.ocm.warehouse.dto.LogisticsDTO;
import com.ocm.warehouse.entity.LogisticsDetail;
import com.ocm.warehouse.entity.Stock;
import com.ocm.warehouse.entity.Warehouse;
import com.ocm.warehouse.service.ILogisticsDetailService;
import com.ocm.warehouse.service.IStockService;
import com.ocm.warehouse.service.IWarehouseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ocm.warehouse.entity.Logistics;
import com.ocm.warehouse.vo.LogisticsVO;
import com.ocm.warehouse.wrapper.LogisticsWrapper;
import com.ocm.warehouse.service.ILogisticsService;
import com.ocm.core.boot.ctrl.BladeController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author HQY
 * @since 2021-11-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/logistics")
@Api(value = "运单管理", tags = "接口")
public class LogisticsController extends BladeController {

	private final ILogisticsService logisticsService;

	private final ILogisticsDetailService logisticsDetailService;

	private final IWarehouseService WarehouseService;

	private final IStockService iStockService;
	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入logistics")
	public R<LogisticsVO> detail(Logistics logistics) {
		Logistics detail = logisticsService.getOne(Condition.getQueryWrapper(logistics));
		return R.data(LogisticsWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入logistics")
	public R<IPage<LogisticsVO>> list(Logistics logistics, Query query) {
		IPage<Logistics> pages = logisticsService.page(Condition.getPage(query), Condition.getQueryWrapper(logistics));
		return R.data(LogisticsWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入logistics")
	public R<IPage<LogisticsVO>> page(@ApiIgnore @RequestParam Map<String, Object>  logistics, Query query,BladeUser bladeUser) {

		QueryWrapper<LogisticsVO> queryWrapper;
		Object status;
		//将status字段转为标准sql字段
		if(logistics.containsKey("status")){
			status=logistics.get("status");
			logistics.remove("status");
			queryWrapper=Condition.getQueryWrapper(logistics, LogisticsVO.class).eq("l.status",status);
		}else
			queryWrapper=Condition.getQueryWrapper(logistics, LogisticsVO.class);

		//判断查询是当前用户运单或仓库运单
		if(logistics.containsKey("l.createUser")){
			logistics.put("l.createUser",bladeUser.getUserId());
			queryWrapper.eq("l.is_deleted",0);
		}else {
			queryWrapper.eq("w.create_user",bladeUser.getUserId());
		}
		IPage<LogisticsVO> pages = logisticsService.selectLogisticsPage(Condition.getPage(query),
			queryWrapper);
		return R.data(pages);
	}

	@PostMapping("/audit")
	@ApiOperationSupport(order = 10)
	@Transactional
	@ApiOperation(value = "审核", notes = "")
	public R audit(@Valid @RequestBody Logistics logistics,BladeUser user) {
		//客服仅能修改以下内容
		Logistics l = new Logistics();
		l.setId(logistics.getId());
		l.setStatus(logistics.getStatus());
		l.setAuditRemark(logistics.getAuditRemark());
		if(logistics.getStatus()==2){
			List<LogisticsDetail> details = logisticsDetailService.list(
				new QueryWrapper<LogisticsDetail>()
					.eq("logistics_id", logistics.getId()).eq("is_deleted",0)
			);
			List<Stock> stocks=new ArrayList<>();

			//根据运单判断运单内商品是否存在仓库
			details.forEach(t->{
				Stock stock = iStockService.getOne(new QueryWrapper<Stock>().eq("sku_id", t.getSkuId()).eq("is_deleted", 0));
				if(stock==null){
					//不存在本商品 新建库存信息
					Stock stock1 = BeanUtil.copy(t, Stock.class).setVersion(0L);
					stock1.setCreateTime(new Date());
					stock1.setCreateUser(user.getUserId());
					stocks.add(stock1);
				}else if(stock.getWarehouseId().equals(t.getWarehouseId())){
					//存在本商品，库存更新
					iStockService.updateById(stock.setStockNumber(t.getStockNumber()+stock.getStockNumber()));
				}else{
					//存在本商品且不在本仓库
					throw new ServiceException("该商品已注册其他仓库,请联系客户协商");
				}
			});
			if(stocks.size()>0)
				iStockService.saveBatch(stocks);
		}
		return R.status(logisticsService.updateById(l));
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入logistics")
	@Transactional
	public R save(@Valid @RequestBody LogisticsDTO logisticsDTO) {

		//只要无需密码仓库数量>0或密码验证正确仓库>0
		if(WarehouseService.count(new QueryWrapper<Warehouse>()
			.eq("id",logisticsDTO.getWarehouseId())
			.eq("oauth",0)
			.eq("status",1)
			.eq("is_deleted",0))>0||
			WarehouseService.count(new QueryWrapper<Warehouse>()
			.eq("id",logisticsDTO.getWarehouseId())
			.eq("warehouse_password",logisticsDTO.getWarehousePassword())
			.eq("status",1)
			.eq("is_deleted",0))>0
		){
			logisticsService.save(logisticsDTO);
			List<LogisticsDetail> details=logisticsDTO.getDetails().stream().peek(
				t->{
					t.setLogisticsId(logisticsDTO.getId());
					t.setWarehouseId(logisticsDTO.getWarehouseId());
				} ).collect(Collectors.toList());
			logisticsDetailService.saveBatch(details);
			return R.success("添加成功,请耐心等待审核");
		}
		return R.fail("密码错误");


	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入logistics")
	public R update(@Valid @RequestBody Logistics logistics) {

		return R.status(logisticsService.updateById(logistics));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改", notes = "传入logistics")
	public R submit(@Valid @RequestBody Logistics logistics) {
		if(logistics.getStatus()==2){
			return R.fail("已入库的运单不允许修改");
		}
		return R.status(logisticsService.updateById(logistics));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(logisticsService.deleteLogic(Func.toLongList(ids)));
	}


}
